<template>
  <div>
    <el-card class="search-card">
      <basic-table-form
        ref="formData"
        isScalingBtn
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm"
        :handleClearForm="handleClearForm"
        @getFormData="getFormData"
      >
        <RemoteSelect
          ref="remoteSelect"
          slot="selectSupplier"
          placeholder="请选择供应商"
          :optionKeys="['supplierName', 'supplierNo']"
          :echoValue="formData.supplierNo"
          :echoOptions="[formData.supplierName, formData.supplierNo]"
          :remoteSelectOptions="remoteOptionsBySupplier"
          :handleClickButton="handleChooseSupplier"
          @getSelect="getSupplierInfoByRemote"
        />
      </basic-table-form>
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="460"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button
            v-if="showBtn('导出')"
            :loading="exportLoading"
            type="primary"
            size="mini"
            @click="handleExport"
            >导出</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleBatchAdd"
            >批量新增</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleBatchEdit"
            >批量修改</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleSeniorLinked"
            >高级关联</el-button
          >
        </div>
      </basic-table>
    </el-card>
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getSeniorResultFn"
    />
    <SelectSupplierDialog
      :visible.sync="dialogVisible.supplier"
      :isAuth="1"
      @getSupplierInfo="getSupplierInfoByDialog"
    />
  </div>
</template>
<script>
import BasicTableForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import RemoteSelect from '@/pages/commodity/components/RemoteSelect';
import SelectSupplierDialog from '@/pages/commodity/components/SelectSupplierDialog';
import {
  FORM_ITEM_LIST,
  TABLE_COLUMNS,
} from './constants';
import { mapGetters } from 'vuex';
import { getSearchParamBySearchType } from '@/utils/getUtils';
import BasePage from '@/mixins/commodity/basePage';
import {
  getAcceptanceCriteriaListService,
  exportAcceptanceCriteriaInfoService
} from '@/api/commodity/acceptanceCriteriaManage/acceptanceCriteriaManage';
import { createExcelByExport, generateUuid, setAuthBtnId } from '@/utils/bizUtils';
import { querySupplierService } from '@/api/commodity/common';

export default {
  mixins: [ BasePage ],
  components: {
    BasicTableForm,
    BasicTable,
    SeniorLinkedDialog,
    RemoteSelect,
    SelectSupplierDialog
  },
  data () {
    return {
      batchSubmitLoading: false,
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        selection: [],
        columns: TABLE_COLUMNS,
        loading: false
      },
      formData: {
        supplierNo: '',
        supplierName: '',
        categoryPath: '',
        spuNo: '',
        skuNo: '',
        productName: '',
        brandName: '',
      },
      seniorLinked: {
        visible: false,
        columns: [{
          label: 'SKU编码',
          prop: 'skuNo',
          type: 'textarea'
        }],
        dataSource: [{ skuNo: '' }],
        isSenior: false,
        skuNos: []
      },
      dialogVisible: {
        supplier: false
      }
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  created () {
    // this.getTableData();
  },
  methods: {
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      return <div class="table-action"><el-button type="text" onClick={() => this.viewDetail(row)}>查看</el-button></div>;
    },
    // 获取表格数据
    async getTableData (skuNos = []) {
      const data = {
        searchParam: JSON.stringify([
          ...getSearchParamBySearchType(FORM_ITEM_LIST, this.formData),
          ...this.getSkuNosParam(skuNos)
        ]),
        ...this.pagination
      };
      setAuthBtnId('查询');
      const retData = await getAcceptanceCriteriaListService(
        data,
        state => { this.tableInfo.loading = state; }
      );
      if (retData) {
        this.tableInfo.list = retData.results;
        this.pagination.totalNum = retData.totalNum;
      }
    },
    // 导出
    handleExport () {
      setAuthBtnId('查询');
      const data = { searchParam: JSON.stringify(
        this.seniorLinked.isSenior ?
          [...this.getSkuNosParam(this.seniorLinked.skuNos)] :
          [...getSearchParamBySearchType(FORM_ITEM_LIST, this.formData)]
      ) }
      console.log(data)
      this.exportInfoData(data);
    },
    // 导出信息数据
    async exportInfoData (data) {
      const res = await exportAcceptanceCriteriaInfoService(
        data,
        state => { this.exportLoading = state; }
      );
      createExcelByExport({ res, excelTitle: `验收标准管理信息_${generateUuid()}` });
    },
    // 批量新增验收标准
    handleBatchAdd () {
      this.$router.push({ name: 'batchAddAcceptance' })
    },
    // 批量修改验收标准
    handleBatchEdit () {
      this.$router.push({ name: 'batchEditAcceptance' })
    },
    // 查看
    viewDetail (row) {
      let routeData = this.$router.resolve({
        path: '/commodity/acceptanceCriteria/acceptanceCriteriaManage/acceptanceCriteriaManageViewY',
        query: {
          uuids: row.uuid,
          orderType: row.orderType,
          recordNo: row.recordNo
        }
      });
      window.open(routeData.href, '_blank');
    },
    // 获取skuNos参数
    getSkuNosParam (skuNos) {
      const skuNosStr = skuNos.join(',')
      return [
        { name: 'skuNosStr', value: skuNosStr },
        { name: 'skuNosStr_q', value: 'EQ' }
      ]
    },
    // 高级关联
    handleSeniorLinked () {
      this.seniorLinked.visible = true;
    },
    // 获取高级关联结果
    getSeniorResultFn (skuNos) {
      this.seniorLinked.skuNos = skuNos
      this.seniorLinked.isSenior = true;
      this.getTableData(skuNos);
    },
    // 表单特殊清空
    handleClearForm () {
      this.clearSupplierInfo();
    },
    // 选择供应商
    handleChooseSupplier () {
      this.dialogVisible.supplier = true;
    },
    // 远程搜索供应商
    async remoteOptionsBySupplier (queryString, loadingFn) {
      const data = {
        nowPage: 1,
        pageShow: 20,
        searchParam: JSON.stringify([
          { name: 'supplierName', value: queryString },
          { name: 'supplierName_q', value: 'Like' }
        ]),
        isAuth: 1
      };
      const res = await querySupplierService(data, loadingFn);
      if (res?.retData) return res.retData.results ?? [];
      return [];
    },
    // 获取远程搜索选择的供应商信息
    getSupplierInfoByRemote (data) {
      this.formData.supplierNo = data.supplierNo;
      this.formData.supplierName = data.supplierName;
    },
    // 获取弹框选择的供应商信息
    getSupplierInfoByDialog (data) {
      this.formData.supplierNo = data.supplierNo;
      this.formData.supplierName = data.supplierName;
    },
    // 清空供应商信息
    clearSupplierInfo () {
      this.$refs.remoteSelect.clearValue()
    }
  }
};
</script>
